<template>
  <div>
    <div style="display: flex;">
      <div
        class="tag"
        :class="{ 'tag-select': isSelectAll }"
        @click="onclick('全部')"
      >
        全部
        <a-icon type="close" class="delete-btn" />
      </div>
      <div
        v-for="(item, index) in list"
        :key="`tag-${item}`"
        class="tag"
        :class="{ 'tag-select': tags[index] ? tags[index].checked : false }"
        @click="onclick(index)"
      >
        {{ item }}
        <a-icon type="close" class="delete-btn" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Model } from 'vue-property-decorator'

@Component({
  components: {},
})
export default class ModelATagGroupndAlgo extends Vue {
  @Prop() list!: any
  // @Prop() value!: any
  // 双向绑定
  @Model('change', { type: Array }) readonly value!: any

  private tags: any = []
  private selectTags: any = []
  public isSelectAll: boolean = this.value.length === 0

  public created() {
    this.init()
  }
  public onclick(index: any) {
    this.selectTags = []
    if (index === '全部') {
      this.isSelectAll = true
      // this.isSelectAll = !this.isSelectAll
      if (this.isSelectAll) {
        this.clearSelection()
      }
      this.selectTags = this.isSelectAll ? 'all' : ''
    } else if (this.tags.length > 0) {
      this.tags[index].checked = !this.tags[index].checked
      if (this.tags[index].checked) {
        this.isSelectAll = false
      }
      this.tags.forEach((item: any) => {
        if (item.checked) {
          this.selectTags.push(item.title)
        }
      })

      if (this.selectTags.length === 0) {
        this.isSelectAll = true
      }
    }
    this.$emit('change', this.selectTags)
    this.$emit('field-change', this.selectTags)
  }
  public init() {
    this.tags = []
    this.list.forEach((element: any) => {
      this.tags.push({
        title: element,
        checked: this.value[0] === element,
      })
    })
  }

  public clearSelection() {
    this.tags = []
    this.list.forEach((element: any) => {
      this.tags.push({
        title: element,
        checked: false,
      })
    })
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.tag {
  border: 1px solid #fff;
  float: left;
  margin-right: 8px;
  padding: 4px 20px;
  position: relative;
  position: relative;
  // text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    background-color: rgba(103, 113, 252, 0.1);
    color: #6973ff;
    cursor: pointer;
  }

  .delete-btn {
    display: none;
    position: absolute;
    right: 2px;
    top: 8px;
  }
}

.tag-select {
  background: rgba(103, 113, 252, 0.1);
  border: 1px solid #6571ff;
  border-radius: 2px;

  .delete-btn {
    display: none;
    position: absolute;
    right: 2px;
    top: 8px;
  }

  // &:hover {
  //   .delete-btn {
  //     display: inline-block;
  //   }
  // }
}
</style>
